var HmonRequest = function () {
    var kid = '2013080116';
    var pwd = 'y7gNCF03tGkAJBfVwWbUB13T0STfI2';
    var path = '/v1/stream/metric/query';

    return {
        buildPostData: function (metric, start, end, tags, aggregator, multiple) {
            var query = {
                metric: metric,
                start: start,
                end: end,
                tags: tags,
                aggregator: aggregator.aggregator,
                rate: aggregator.rate
            }
            if (multiple > 1) {
                query.downsample_delta = multiple + 'm';
                query.downsample_agg = aggregator.downsample_agg;
            }
            return JSON.stringify(query);
        },
        initSeries: function (chart, seriesName, postData) {
            var sinawatch = new $.SinaWatch();
            sinawatch.bind_auth(kid, pwd);

            sinawatch.post({
                action: path,
                data: {query: postData},
                done: function (spans) {
                    var seriesData = [];
                    $.each(spans, function (_, span) {
                        $.each(span.timevalue, function (idx, val) {
                            $.each(val, function (k, v) {
                                seriesData.push({x: parseInt(k) * 1000, y: v});
                            });
                        });
                    });
                    chart.addSeries({name: seriesName, data: seriesData});
                },
                error: function (data) {
                    // something goes wrong.
                    console.log(data);
                },
                always: function () {
                    // it's would be called everytime.
                }
            });
        },
        updateSeries: function (series, postData) {
            var sinawatch = new $.SinaWatch();
            sinawatch.bind_auth(kid, pwd);

            sinawatch.post({
                action: path,
                data: {query: postData},
                done: function (spans) {
                    var seriesData = [];
                    $.each(spans, function (_, span) {
                        $.each(span.timevalue, function (idx, val) {
                            $.each(val, function (k, v) {
                                seriesData.push({x: parseInt(k) * 1000, y: v});
                            });
                        });
                    });
                    series.setData(seriesData, true);
                },
                error: function (data) {
                    // something goes wrong.
                    console.log(data);
                },
                always: function () {
                    // it's would be called everytime.
                }
            });
        }
    };
}();